/**
 * Copyright (c) Software Institute of PKU
 * All rights reserved. 
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 */
package edu.pku.sei.modeler.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;

import edu.pku.sei.modeler.exceptions.FactoryNotFoundException;
import edu.pku.sei.modeler.model.common.ModelRegistry;
import edu.pku.sei.modeler.model.core.MetaModel;
import edu.pku.sei.modeler.model.core.MetaPackage;
import edu.pku.sei.modeler.model.structure.MetaDiagram;
import edu.pku.sei.modeler.model.structure.StructureFactory;
import edu.pku.sei.modeler.project.ProjectRegistry;

/**
 * @author zl
 *
 */
public class DiagramCreateAction extends Action {
	IWorkbenchPage workbenchPage;
	private String diagType;
	private Object obj;
	
	public IWorkbenchPage getWorkbenchPage() {
		return workbenchPage;
	}
	public void setWorkbenchPage(IWorkbenchPage workbenchPage) {
		this.workbenchPage = workbenchPage;
	}
	public DiagramCreateAction(String diagramType){
		super();
		this.setText("Create a "+diagramType+" Diagram");
		setToolTipText("Create a "+diagramType+" Diagram");
		this.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
				getImageDescriptor(ISharedImages.IMG_TOOL_PASTE));
		this.diagType = diagramType;
	}
	
	public void setTreeObj(Object obj) {
		this.obj = obj;
	}
//	public TreeViewer getViewer() {
//		return viewer;
//	}

//	public void setViewer(TreeViewer viewer) {
//		this.viewer = viewer;
//	}
	public void run(){
//		if(viewer==null)return;
//		ISelection selection = viewer.getSelection();
//		if(selection==null)return;
//		Object obj = ((IStructuredSelection)selection).getFirstElement();
//		if(obj==null)return;
		if(obj instanceof MetaPackage) {
			MetaModel model = (MetaModel)((MetaPackage)obj).getModel();
			StructureFactory sFactory;
			try {
				sFactory = (StructureFactory)ModelRegistry.getRegistry().getStructureFactory(model);
				MetaDiagram diagram = sFactory.createMetaDiagram();
				diagram.setType(diagType);
//				diagram.setModel(((MetaPackage)obj).getModel());
				// add diagram to the package
				((MetaPackage)obj).getDiagrams().add(diagram);
				// add diagram to the project ( for open an editor )
				ProjectRegistry.getDefault().openDiagram(diagram, model);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FactoryNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
